// miniprogram/pages/startGame/startGame.js
const app = getApp()
var watcher = null

Page({
  data: {
    title: "",
    room: "", // 房间id
    height: "130rpx",
    memberNum: 0,  // 当前房间设置的可加入人数
    tempArray: [], // 存储临时的空用户信息
    userArray: [], // 存储当前加入房间的用户信息
    messageArray: [], // 存储用户加入房间之后房间内所产生的信息集合
    joinUser: [],  // 存储加入房间时，房间内已有的用户列表（包括自己）
    joinMessage: {},  // 存储当前用户加入房间时的 join消息（即广播给其他用户的加入房间的消息）
    isOwner: true,
  },

  onLoad: function(options) {
    this.setData({
      room: options.room,
      title: "房间" + options.room
    })
    this.queryRoom()
    this.addMessageWatcher()
  },

  onShow: function () {
    // 设置头像宽高比 1:1
    var that = this
    var gridGap = 10 / 750 * wx.getSystemInfoSync().windowWidth
    setTimeout(function() {
      var query = wx.createSelectorQuery()
      query.select("#table").boundingClientRect(function (rect) {
        if (rect == null) return
        that.setData({
          height: (rect.width / 5 - gridGap) + "px"
        })
      }).exec()
    }, 800)
  },

  onUnload: function(options) {
    if (watcher != null) watcher.close()
  },

  queryRoom: async function () {
    var that = this
    wx.showLoading({
      title: '加载中...',
    })
    const db = wx.cloud.database()
    db.collection("room").doc(this.data.room).get({
      success: function (res) {
        console.log('[云数据库] [room] 查询: ', res)
        var userArr = []
        var tempArr = []
        for (var i = 0; i < res.data.totalNum; i++) {
          userArr.push({nickname: "昵称", avatar: ""});
          tempArr.push({nickname: "昵称", avatar: ""});
        }
        const isOwner = (res.data.owner == app.globalData.openid)
        that.setData({
          memberNum: res.data.totalNum,
          userArray: userArr,
          tempArray: tempArr,
          isOwner: isOwner
        })
        that.queryUser()
      },
      fail: function (res) {
        console.log('[云数据库] [room] 查询失败: ', res)
        wx.hideLoading()
      }
    })
  },

  queryUser: async function() {
    var that = this
    const db = wx.cloud.database()
    db.collection("user").where({
      status: "ready",
      room: this.data.room
    }).get({
      success: function (res) {
        console.log('[云数据库] [user] 查询: ', res)
        wx.hideLoading()
        const userArr = res.data.concat(that.data.tempArray).splice(0, that.data.memberNum)
        const message = {msgContent: app.globalData.userInfo.nickName + "  加入房间"}
        that.setData({
          userArray: userArr,
          messageArray: [message],
          joinMessage: message,
          joinUser: res.data
        })
      },
      fail: function (res) {
        console.log('[云数据库] [user] 查询失败: ', res)
        wx.hideLoading()
      }
    })
  },

  addMessageWatcher: async function() {
    var that = this
    const db = wx.cloud.database()
    const _ = db.command
    watcher = db.collection("message").where({
      room: this.data.room,
      sendTimeTS: _.gt(Date.now()) 
    }).watch({
      onChange: snapshot => {
        console.log('[云数据库] [message] 新事件: ', snapshot)
        that.handleMessage(snapshot)
      },
      onError: err => {
        console.error('[云数据库] [message] 监听错误: ', err)
      }
    })
  },
  
  handleMessage: function(snapshot) {
    const messageArr = snapshot.docs
    if (messageArr.length <= 0) return
    console.log('消息列表: ', messageArr)
    var tempArr = this.data.tempArray
    var userArr = this.data.joinUser

    // 页面跳转命令
    const message = messageArr[messageArr.length - 1]
    if (message.msgType == "command-show-loading") {
      wx.showLoading({
        title: '游戏加载中...',
      })
    }
    if (message.msgType == "command-hide-loading") {
      wx.hideLoading()
      wx.showToast({
        icon: 'none',
        title: '游戏加载失败',
        duration: 2000
      })
    }
    if (message.msgType == "command-page-playGame") {
      wx.hideLoading()
      wx.reLaunch({url: '../playGame/playGame?room=' + this.data.room})
    }

    for (const item in messageArr) {
      // 如果是加入房间的消息，则将新加入的用户添加到队列中
      if (messageArr[item].msgType == "command-join") {
        // 过滤到已经添加过的用户
        var arr = userArr.filter((user) => {
          return user._openid == messageArr[item].sender;
        })
        if (arr.length <= 0) userArr.push(messageArr[item])
      }
      // 如果是离开房间的消息，则将离开的用户移除队列
      if (messageArr[item].msgType == "command-leave") {
        userArr = userArr.filter((user) => {
          return user._openid != messageArr[item].sender;
        })
      }
    }
    userArr = userArr.concat(tempArr).splice(0, this.data.memberNum);
    this.setData({
      userArray: userArr,
      messageArray: [this.data.joinMessage].concat(messageArr)
    });
  },

  changeUserStatus: async function() {
    wx.cloud.callFunction({
      name: "modifyUser",
      data: {
        status: "normal",
        room: "0",
        solve: false,
      },
      success: function (res) {
        console.log('[云函数] [modifyUser] 调用: ', res)
      },
      fail: function (res) {
        console.log('[云函数] [modifyUser] 调用失败: ', res)
      }
    })
  },

  sendMessage: function(command, msgContent) {
    const db = wx.cloud.database()
    db.collection("message").add({
      data: {
        room: this.data.room,
        sender: app.globalData.openid,
        msgType: command,
        msgContent: msgContent != null ? msgContent : "",
        nickname: app.globalData.userInfo.nickName,
        avatar: app.globalData.userInfo.avatarUrl,
        sendTime: new Date(),
        sendTimeTS: Date.now()
      },
      success: function (res) {
        console.log('[云数据库] [message] 插入: ', res)
      },
      fail: function (res) {
        console.log('[云数据库] [message] 插入失败: ', res)
      }
    })
  },

  onExitRoom: function() {
    var that = this
    wx.showModal({
      title: '提示',
      content: '是否继续退出房间',
      success (res) {
        if (res.confirm) {
          if (watcher != null) watcher.close()
          that.changeUserStatus()
          that.sendMessage("command-leave", app.globalData.userInfo.nickName + "  离开房间")
          wx.reLaunch({url: '../index/index'})
        }
      }
    })
  },

  onStartGame: async function() {
    const db = wx.cloud.database()
    var result = await db.collection("user").where({
      status: "ready",
      room: this.data.room
    }).get()
    console.log("onStartGame user size: ", result.data.length)
    console.log("onStartGame room size: ", this.data.memberNum)
    if (result.data.length != this.data.memberNum) {
      wx.showToast({
        icon: 'none',
        title: '当前房间为坐满，无法开始游戏!',
        duration: 3000
      })
      return
    } 
    this.sendMessage("command-show-loading")
    wx.cloud.callFunction({
      name: 'assignCards',
      data: {
        room: this.data.room
      },
      success: res => {
        console.log('[云函数] [assignCards] : ', res)
        wx.hideLoading()
        if (res.result) {
          wx.reLaunch({url: '../playGame/playGame?room=' + this.data.room})
          this.sendMessage("command-page-playGame")
        }
      },
      fail: err => {
        console.error('[云函数] [assignCards] 调用失败', err)
        this.sendMessage("command-hide-loading")
      }
    })
  },
})